package pri.abner.practice.thread.threadImpl;

import java.util.concurrent.*;

/**
 * @description 
 * @author  Abner Chow
 * @date Created in 2018/11/13 15:47
 * @version v1.0.0
 */
public class ThreadMainApp {
    public static void main(String[] args) {

        System.out.println("主线程开始启动");

        new ThreadA("线程A").start();

        Thread b = new Thread(new RunnableA());
        b.setName("线程B");
        b.start();

        FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "获取到CPU资源");
                for (int i = 0; i < 200; i++) {
                    System.out.println( Thread.currentThread().getName() + "实现有返回值的线程" + i);
                }
                Thread.sleep(2000);
                throw new RuntimeException("出错了");
                /*return 12;*/
            }
        });
        //使用FutureTask对象作为target来创建并且启动线程
        Thread c = new Thread(task);
        c.setName("线程C");
        c.start();
        try{
            // .get() 调用该方法将导致程序(主线程)阻塞，必须等到子线程结束后才会得到返回值
            //主线程设置2008毫秒未能获取结果自动超时
            int getResult = task.get(2008 , TimeUnit.MILLISECONDS);
            System.out.println("主线程获取返回结果" + getResult);
        }catch ( InterruptedException  | ExecutionException | TimeoutException e  ){
            System.out.println(e.toString());
            e.printStackTrace();
        }
        System.out.println("主线程完结");


    }

}
